package com.gok.pay.controller;

import com.alibaba.fastjson.JSONObject;
import com.gok.pay.service.ITestService;
import com.gok.persistence.service.IBaseService;
import com.gok.util.Funutil;
import com.sy.shiro.UsernameToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by mac on 2018/1/9.
 */
@Controller
@Slf4j
@RequestMapping("/")
public class LoginController
{
    @Resource
    private IBaseService baseService;
    @Resource
    private ITestService testService;

    @RequestMapping(value="/", method = RequestMethod.GET)
    public
//    @ResponseBody
    String veriphone (HttpServletRequest request, HttpServletResponse response){
        UsernameToken usernameToken = testService.getUser();
        if( usernameToken == null ){
            return "login";
        }
        return "index";

    }


    /**
     * 验证码
     *
     * @param request
     * @param response
     * @param model
     * @throws Exception
     */
    @RequestMapping(value = "/vericode", method = RequestMethod.GET)
    public
    @ResponseBody
    void vericode(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {


        UsernameToken juejinuser = testService.getUser();
        int a = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;//产生1000-9999的随机数
        request.setAttribute("vericode", a);

        String phone = "";

        if (juejinuser == null) {
            phone = request.getParameter("phone");
        } else {
            phone = juejinuser.getPhone();
        }

        Funutil.send_newsms(phone, a + "");

    }


    /**
     * 验证手机号码
     *
     * @param request
     * @param response
     * @param model
     * @throws Exception
     */
    @RequestMapping(value = "/loginaction", method = RequestMethod.GET)
    public
    @ResponseBody
    void loginaction(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        String vericode = request.getParameter("vericode");
        String phone = request.getParameter("phone");
        if( vericode.equals(request.getSession().getAttribute("vericode")) ){
            SecurityUtils.getSubject().login(new UsernameToken(phone, vericode, (long) 0));
        }
    }


    }
